<template>
    <table class="main-table table-form stu-form">
        <caption>指导老师</caption>
        <colgroup>
            <col width="47px">
            <col width="150px">
            <col width="150px">
            <col width="100px">
        </colgroup>
        <thead>
            <tr>
                <th>序号</th>
                <th>工号</th>
                <th>姓名</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(v, k) in members">
                <td>{{ v.memberOrder }}</td>
                <td>
                    <a-input v-model:value="v.code" :readonly="isReadOnly(v)" :bordered="false" :show-count="!isReadOnly(v)" :maxlength="30"
                        @preeEnter="getUserByCode(v, TEACHER)" @blur="!isReadOnly(v) && getUserByCode(v, TEACHER)" />
                </td>
                <td>{{ v.realName }}</td>
                <td class="btn-area">
                    <span class="a-btn" v-if="canMoveUp(k)" @click="moveUp(k)">[上移]</span>
                    <span v-else class="a-btn placeholder"></span>
                    <span class="a-btn" v-if="canMoveDown(k)" @click="moveDown(k)">[下移]</span>
                    <span v-else class="a-btn placeholder"></span>
                    <span class="a-btn remove-btn" v-if="!isReadOnly(v) && k !== 0" @click="removeItem(k)">[移除]</span>
                </td>
            </tr>
            <tr v-if="canCreate">
                <td colspan="4" class="text-center a-btn" @click="createEmpty">添加一位指导老师</td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import { ref, reactive, watchEffect, provide, inject } from 'vue';
import useMembers from './useMembers'
import app from '@/app';

const props = defineProps({
    maxCapacity: {
        type: Number,
        default: 5
    }
})

const data = inject("data");
const ROLE_NAME = "教职工";
const {
    members,
    getUserByCode,
    errorStrings,
    createEmpty,
    validate,
    removeItem,
    moveUp,
    moveDown,
    reset,
    canCreate
} = useMembers(data, ROLE_NAME, props.maxCapacity);

function isReadOnly (member) {
    if (app.currentUser.currentRole.Name === ROLE_NAME && member.realName === app.currentUser.RealName) {
        if (member.memberOrder === 1) {
            // 指导老师本人不能改
            return true;
        } else {
            return false;
        }
    }
    
    return false;
}

function canMoveUp (order) {
    return order > (app.currentUser.currentRole.Name === ROLE_NAME ? 1 : 0);
}

function canMoveDown (order) {
    return order < members.value.length - 1 && (app.currentUser.currentRole.Name === ROLE_NAME ? order !== 0 : true);
}

defineExpose({
    validate,
    members,
    reset,
    errorStrings
});
</script>

<style lang="less">
.stu-form {
    .a-btn.placeholder {
        display: inline-block;
        width: 2.5em;
    }
}
</style>